<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="接口名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入接口名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接口方法" prop="httpMethod">
        <el-select
          v-model="queryParams.httpMethod"
          placeholder="请选择接口方法"
          clearable
          @change="handleQuery"
        >
          <el-option label="get" value="get" />
          <el-option label="post" value="post" />
        </el-select>
      </el-form-item>
      <el-form-item label="请求路径" prop="path">
        <el-input
          v-model="queryParams.path"
          placeholder="请输入请求路径"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input
          v-model="queryParams.tags"
          placeholder="请输入标签"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="flex flex-row items-center mb-4">
      <el-button
        type="primary"
        plain
        icon="Plus"
        @click="handleAdd"
        v-hasPermi="['web:db:api:apiDetail:add']"
      >
        新增
      </el-button>
      <el-button
        type="danger"
        plain
        icon="Delete"
        :disabled="multiple"
        @click="handleDelete({})"
        v-hasPermi="['web:db:api:apiDetail:remove']"
      >
        批量删除
      </el-button>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
    </div>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="接口名称" prop="name" align="center" />
      <el-table-column label="接口方法" prop="httpMethod" align="center" />
      <el-table-column label="请求路径" prop="path" align="center" show-overflow-tooltip />
      <el-table-column label="是否加密传输" prop="encrypt" align="center">
        <template #default="{ row }">
          <span>{{ formatBoolean(row.encrypt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="返回数据量" prop="returnSize" align="center">
        <template #default="{ row }">
          <span>{{ formatReturnSize(row.returnSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="查询SQL" prop="sql" align="center" width="200">
        <template #default="{ row }">
          <span
            class="truncate text-blue-400 cursor-pointer"
            @click="showScript(row.sql, '查询SQL')"
          >
            {{ row.sql }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="tags" align="center" />
      <el-table-column label="操作" align="center" fixed="right" width="240">
        <template #default="{ row }">
          <div class="flex flex-row justify-center items-center">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(row)"
              v-hasPermi="['web:db:api:apiDetail:edit']"
            >
              修改
            </el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              style="color: red"
              @click="handleDelete(row)"
              v-hasPermi="['web:db:api:apiDetail:remove']"
            >
              删除
            </el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button link type="primary" icon="Operation" @click="handleSqlTest(row)">
                      SQL测试
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link type="primary" icon="Switch" @click="handleApiTest(row)">
                      接口测试
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link type="primary" icon="CopyDocument" @click="handleApiCopy(row)">
                      接口复制
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pageParams.pageNum"
      v-model:limit="pageParams.pageSize"
      @pagination="getList"
    />

    <script-view v-model="scriptShow" :title="scriptTitle" :content="scriptContent" />

    <detail-api v-model="detailShow" :current-item="detailItem" @success="getList" />

    <test-sql v-model="testSqlShow" :current-item="testSqlItem" />

    <test-api v-model="testApiShow" :current-item="testApiItem" />
  </div>
</template>

<script setup name="ApiList">
  import { ref } from 'vue';
  import { pageApiDetail, getApiDetailInfo, delApiDetail } from '@/api/web/db/api/api-list';
  import DetailApi from './components/detail-api';
  import ScriptView from './components/script-view';
  import TestSql from './components/test-sql';
  import TestApi from './components/test-api';
  import modal from '@/plugins/modal';

  const list = ref([]);
  const total = ref(0);
  const loading = ref(false);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);

  const queryRef = ref(null);
  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const queryParams = ref({
    name: null,
    httpMethod: null,
    path: null,
    tags: null,
  });

  const detailShow = ref(false);
  const detailItem = ref(null);

  const scriptTitle = ref('');
  const scriptShow = ref(false);
  const scriptContent = ref('');

  const testSqlShow = ref(false);
  const testSqlItem = ref(null);

  const testApiShow = ref(false);
  const testApiItem = ref(null);

  function getList() {
    loading.value = true;
    pageApiDetail(pageParams.value, queryParams.value)
      .then((res) => {
        list.value = res?.data?.records ?? [];
        total.value = res?.data?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  function resetQuery() {
    queryRef.value?.resetFields();
    handleQuery();
  }

  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  }

  function handleAdd() {
    detailItem.value = null;
    detailShow.value = true;
  }

  function handleUpdate(row) {
    const _id = row?.id ?? ids.value?.[0];
    getApiDetailInfo(_id).then((res) => {
      detailItem.value = {
        ...res.data,
        apiParams: (res.data?.apiParams ?? []).map((k) => ({ ...k, isEdit: false })),
        apiReturns: (res.data?.apiReturns ?? []).map((k) => ({ ...k, isEdit: false })),
      };
      detailShow.value = true;
    });
  }

  function handleDelete(row) {
    const _ids = row?.id ?? ids.value.join(',');
    modal
      .confirm('是否确认删除所选在线接口？')
      .then(() => {
        return delApiDetail(_ids);
      })
      .then(() => {
        getList();
        modal.msgSuccess('删除成功');
      })
      .catch(() => {});
  }

  function formatBoolean(value) {
    if (value === null || value === undefined) {
      return '';
    }
    return value ? '是' : '否';
  }

  function formatReturnSize(value) {
    if (value === 'one') {
      return '单条';
    } else if (value === 'more') {
      return '多条';
    } else {
      return '';
    }
  }

  function showScript(content, title) {
    scriptContent.value = content;
    scriptTitle.value = title;
    scriptShow.value = true;
  }

  function handleSqlTest(row) {
    getApiDetailInfo(row.id).then((res) => {
      testSqlItem.value = res.data;
      testSqlShow.value = true;
    });
  }

  function handleApiTest(row) {
    getApiDetailInfo(row.id).then((res) => {
      testApiItem.value = res.data;
      testApiShow.value = true;
    });
  }

  function handleApiCopy(row) {
    getApiDetailInfo(row.id).then((res) => {
      detailItem.value = {
        ...res.data,
        id: null,
        apiParams: (res.data?.apiParams ?? []).map((k) => ({
          ...k,
          id: null,
          apiId: null,
          isEdit: false,
        })),
        apiReturns: (res.data?.apiReturns ?? []).map((k) => ({
          ...k,
          id: null,
          apiId: null,
          isEdit: false,
        })),
      };
      detailShow.value = true;
    });
  }

  getList();
</script>

<style scoped lang="scss"></style>
